/*
 *  Functions related to the map
 * 
 */

// initialazing map

var tileLayer = L.tileLayer('http://{s}.tile.cloudmade.com/BC9A493B41014CAABB98F0471D759707/997/256/{z}/{x}/{y}.png', {
			maxZoom: 18,
			attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery Â© <a href="http://cloudmade.com">CloudMade</a>'
			});

var registrationLayer = new L.LayerGroup(); // temp marker where you add thing
var existingLayer = new L.LayerGroup(); // collect all existing markers
//var markersGroup = new L.MarkerClusterGroup();

var map = new L.Map('map', {
    center: new L.LatLng(39.90973623453719, -93.69140625),
    zoom: 3,
    layers: [tileLayer, registrationLayer, existingLayer]
	//layers: [tileLayer, registrationLayer, markersGroup]
	});

// localizing the user
map.locate({setView: true, maxZoom: 16}); // setView: true, shorcut to ask to locate the user

// refresh list on move end
init_onMoveEnd();

function evalDistance()
{
	var distance = 10000;
	switch(map.getZoom())
	{
		case 18: distance=200; break;
		case 17: distance=200; break;
		case 16: distance=500; break;
		case 15: distance=2000; break;
		case 14: distance=8000; break;
		case 13: distance=32000; break;
		case 12: distance=128000; break;
		case 11: distance=512000; break;
		case 10: distance=2048000; break;
		default: distance=10000; break;
	}
	return distance;
}

function displayOnMap()
{
	existingLayer.clearLayers();
	//markersGroup.clearLayers(); // cleaning the layer
	bounds=map.getBounds();				
	for(i in things)
	{
		if (bounds.contains(things[i].latlng))
		{
			var markerLocation = new L.LatLng(things[i].lat, things[i].lng);
			var marker = new L.Marker(markerLocation);
			// Message
			var msg = '<div id="thing_popup">'
			+ '<img src="" />'
			+ '<strong>' + things[i].title + '</strong></br>'
			+ things[i].description + '</br>'
			+ 'by ' + things[i].username + '<div/>';

			//	things[i].id+" - "+;

			
		    marker.bindPopup(msg);
		    
		    //markersGroup.addLayer(marker);
		    existingLayer.addLayer(marker);
		    things[i].setMarker(marker);
		}
	}
	
	//existingLayer.addLayer(markersGroup);
	//things[0].marker.openPopup(); we can access the object marker through our object thing :)
}

/*
 *  Create an object
 *  
 */

var registrationMarker = new L.Marker([0,0]);

registrationMarker.options.draggable = true;
var firstClick = true;
function onMapClick(e)
{
	var markerLocation = new L.LatLng(e.latlng.lat, e.latlng.lng);
	registrationMarker.setLatLng(markerLocation);
    registrationLayer.clearLayers();
    registrationLayer.addLayer(registrationMarker);	
	var msg = 'Your object will be added here! You can still move it';
			
	registrationMarker.bindPopup(msg, {closeButton: false}).openPopup();
	
	if(firstClick)
	{
		firstClick = false;
		$('#register_area').html('<img class="center" src="assets/img/ajax-loader.gif">');
	    $('#register_area').load('pages/view_part/register');
	}
}

/*
 *  Others
 * 
 */

function onMoveEnd(e)
{
	mapCenter = map.getCenter();
	$('#debuglive').html('<p>'+mapCenter+'</p>');
	refreshList(sortBy, param);
}

function init_onMoveEnd()
{
	map.addEventListener('moveend', onMoveEnd);
	//map.on('moveend', onMoveEnd);
}

function cancel_onMoveEnd()
{
	map.removeEventListener('moveend', onMoveEnd);
}

function locate(thing_id)
{
	latLng = [things[thing_id].lat, things[thing_id].lng];
	map.panTo(latLng);
	displayOnMap();
}

function location_search(string)
{
	//alert(string);
	var bounds = map.getBounds();
	NW = bounds.getNorthWest();
	NWlat = bounds.getNorthWest().lat;
	NWlng = bounds.getNorthWest().lng;
	SElat = bounds.getSouthEast().lat;
	SElng = bounds.getSouthEast().lng;
	bounds = new Array(NWlat, NWlng, SElat, SElng);
	
	$.ajax({
		url: 'http://open.mapquestapi.com/geocoding/v1/address',
		dataType: 'jsonp',
		crossDomain: true,
		data: {
			location : string,
			boundingBox: {
				ul:{
					lat:NWlat,
					lng:NWlng},
				lr:{
					lat:SElat,
					lng:SElng}
				},
			maxResults : 1
		},
		timeout: 3000,
		success: function(data)
		{
			lat = data.results[0].locations[0].latLng.lat;
			lng = data.results[0].locations[0].latLng.lng;
			latLng = [lat, lng];
			map.panTo(latLng);
			map.setZoom(12);
			display_alert('location found', '#alert_area', 'success');
		},
        error: function() { display_alert('connexion problem', '#alert_area', 'error'); }
	});
}